import os
import re
import shutil
import sys
import time
import platform

import auto_log
import auto_vm
import auto_utility
import auto_test

#-----------------------------------------------------
#get system drive
system_drive = auto_utility.get_system_drive()["res"]
if system_drive == "":
    stop_test("")
#-----------------------------------------------------
python_exe = auto_utility.file_from_path(system_drive + "\\Python31", "python.exe")["res"]
#-----------------------------------------------------
utilities = system_drive + "\\" + auto_test.AUTOTEST_UTILITIES
logs = system_drive + "\\" + auto_test.AUTOTEST_LOGS
run = system_drive + "\\" + auto_utility.AUTOTEST_RUN
files_list = system_drive + "\\" + auto_test.AUTOTEST_FILES_LIST
#-----------------------------------------------------

SCRIPTS_RUN = sys.argv[1]
LAYOUT_INI_PATH_NAME = sys.argv[2]

TASK_PATH_NAME = auto_utility.file_from_path(files_list, ".psl")["res"]

STUBACT_PATH_NAME = r"a:\stubact.log"
PWLOG_PATH_NAME = r"a:\pwlog.txt"
SCRIPTS_OUTPUT_PATH_NAME = r"a:\psi.out"
BLUESCREEN_PATH_NAME = r"a:\bluescreen.log"
EXCEPT_PATH_NAME = r"a:\except.txt"
FULLLIST_PATH_NAME = r"a:\fulllist.txt"

CKDSK_FLAG_PATH_NAME = "restart_for_chkdsk.txt"

FOLDER_FOR_LOGS = logs
RESULTS_PATH_NAME = r"a:\autotest_results.xml"

CHKDSK_AFTER_BLUESCREEN = r"chkdsk_after_bluescreen.txt"
CHKDSK_ALL = r"chkdsk_all.txt"

SPLIT_STRING = "// This file"

RESULT_STRING_OK = "Script completes succesfully"
RESULT_STRING_ERROR = "Result = Error"

CHECK_FLOPPY_N = 10

err_no_layout = -1
err_no_format = -2
err_no_psloglist = -3
err_no_scripts = -4
err_scripts_failed = -5
err_except_in_bluescreen = -6
err_reboot_request = -7

#global variables but not constants
SCRIPT_PATH_NAME = TASK_PATH_NAME
START_PY_PATH_NAME = files_list + "\\start.py"
END_PY_PATH_NAME = files_list + "\\end.py"
DATA_PATH_NAME = files_list + "\\data.data"
CORRECT_FULLLIST_PATH_NAME = files_list + "\\correct_fulllist.data"

def compare_fulllist(correct, test):
    try:
        file = open(correct, "r")
        a = file.read()
        file.close()

        file = open(test, "r")
        b = file.read()
        file.close()
    except:
        return("Error! Can't read file")
    
    MB_MAX_DIFF = float(200)
    MB_MAX_DIFF_C = float(200)
    
    temp = a.split("\n")
    list_a = []
    for item in temp:
        if item != "":
            list_a.append(item)
    temp = b.split("\n")
    list_b = []
    for item in temp:
        if item != "":
            list_b.append(item)
    
    #check length
    if len(list_a) != len(list_b):
        print("\nError! Incorrect number of records in fulllist\n")
        message = "<b>Error! Incorrect number of records in fulllist\n\n"
        message = message + "Fulllist after test:</b>\n" + b
        message = message + "\n<b>Correct Fulllist:</b>\n" + a
        return(message)

    #get list of different records
    i = 0
    N = len(list_a)
    diff = []
    while i < N:
        #print(list_a[i], "\n", list_b[i], "\n")
        if list_a[i] != list_b[i]:
            #print(list_a[i], list_b[i])
            diff.append(i)
        i += 1
    
    for record in diff:
        values_a = list_a[record].split("|")
        values_b = list_b[record].split("|")

        if len(values_a) != len(values_b):
            print("\nError! Different record size in fulllist\n")
            message = "<b>Error! Different record size in fulllist\n\n"
            message = message + "Fulllist after test:</b>\n" + b
            message = message + "\n<b>Correct Fulllist:</b>\n" + a
            return(message)
        
        record_size = len(values_a)
        i = 0
        while i < record_size:
            if values_a[i].count(",") == 1:
                values_a[i] = values_a[i].split(",")[0] + "." + values_a[i].split(",")[1]
            if values_b[i].count(",") == 1:
                values_b[i] = values_b[i].split(",")[0] + "." + values_b[i].split(",")[1]
            if values_a[i] != values_b[i]:
                if ((i != 9) and (i != 10)):
                    print("\nError! Different record. Number = " + str(record+1) + " Must be = " + values_a[i] + ", but it is = " + values_b[i] + "\n")
                    message = "<b>Error! Different record. Number = " + str(record+1) + " Must be = " + values_a[i] + ", but it is = " + values_b[i] + "\n\n"
                    message = message + "Fulllist after test:</b>\n" + b
                    message = message + "\n<b>Correct Fulllist:</b>\n" + a
                    return(message)
                else:
                    MB_MAX = MB_MAX_DIFF
                    try:
                        if ((values_a[11] == " C ") and (values_b[11] == " C ")):
                            MB_MAX = MB_MAX_DIFF_C
                    except:
                        MB_MAX = MB_MAX_DIFF
                    size_a = values_a[i].split(" ")
                    size_b = values_b[i].split(" ")
                    
                    if size_a[2] == "MB":
                        size_mb_a = float(size_a[1])
                    elif size_a[2] == "GB":
                        size_mb_a = float(size_a[1])*1024
                    else:
                        print("\nError. Can't compare Used\Free sizes. Record number = " + str(record+1) + "\n")
                        message = "<b>Error! Can't compare Used\Free sizes. Record number = " + str(record+1) + "\n\n"
                        message = message + "Fulllist after test:</b>\n" + b
                        message = message + "\n<b>Correct Fulllist:</b>\n" + a
                        return(message)
                    if size_b[2] == "MB":
                        size_mb_b = float(size_b[1])
                    elif size_b[2] == "GB":
                        size_mb_b = float(size_b[1])*1024
                    else:
                        print("\nError. Can't compare Used\Free sizes. Record number = " + str(record+1) + "\n")
                        message = "<b>Error! Can't compare Used\Free sizes. Record number = " + str(record+1) + "\n\n"
                        message = message + "Fulllist after test:</b>\n" + b
                        message = message + "\n<b>Correct Fulllist:</b>\n" + a
                        return(message)
                    if (abs(size_mb_a - size_mb_b) > MB_MAX):
                        print("\nError. Different in Used\Free is too much. Record number = " + str(record+1) + "\n")
                        message = "<b>Error! Different in Used\Free is too much. Record number = " + str(record+1) + "\n\n"
                        message = message + "Fulllist after test:</b>\n" + b
                        message = message + "\n<b>Correct Fulllist:</b>\n" + a
                        return(message)
            i += 1
    
    return 0
#----------------------------------------------------------------------

def get_contents_from_task(data, start, end):
    result = ""
    if data.count(start) == 1:
        result = data.split(start)[1]
        if result.count(end) == 1:
            result = result.split(end)[0]
            return result
        else:
            return ("")
    else:
        return ("")
#----------------------------------------------------------------------

def parse_task():
    if (os.path.exists(START_PY_PATH_NAME)):
        return 0
    if (os.path.exists(END_PY_PATH_NAME)):
        return 0
    
    print("Parse task file\n")
    file = open(TASK_PATH_NAME, "r")
    data = file.read()
    file.close()
    
    #not scripts
    not_scripts_start = "<not scripts>\n"
    not_scripts_end = "</not scripts>"
    
    #start.py
    start_py_start = "<start.py>\n"
    start_py_end = "</start.py>"
    
    #end.py
    end_py_start = "<end.py>\n"
    end_py_end = "</end.py>"
    
    #data.data
    data_start = "<data>\n"
    data_end = "</data>"
    
    #correct fulllist
    fulllist_start = "<fulllist>\n"
    fulllist_end = "</fulllist>"
    
    
    if data.count(not_scripts_start) == 0:
        print("There are no python scripts in task\nParse task. Done!\n")
        return 0

    #get region script
    region_script = data.split(not_scripts_start)[0]
    file = open(TASK_PATH_NAME, "w")
    file.write(region_script)
    file.close()
    
    #get region for start python script
    start_py = get_contents_from_task(data, start_py_start, start_py_end)
    end_py = get_contents_from_task(data, end_py_start, end_py_end)
    data_data = get_contents_from_task(data, data_start, data_end)
    fulllist = get_contents_from_task(data, fulllist_start, fulllist_end)
    
    if start_py != "":
        file = open(START_PY_PATH_NAME, "w")
        file.write(start_py)
        file.close()
        print("\nThere is nonempty start.py script in task\n")
    else:
        print("\nstart.py is empty")
    
    if end_py != "":
        file = open(END_PY_PATH_NAME, "w")
        file.write(end_py)
        file.close()
        print("\nThere is nonempty end.py script in task\n")
    else:
        print("\nend.py is empty\n")
    
    if data_data != "":
        file = open(DATA_PATH_NAME, "w")
        file.write(data_data)
        file.close()
        print("\nThere is nonempty data.data in task\n")
    else:
        print("\ndata.data is empty\n")
    
    if fulllist != "":
        file = open(CORRECT_FULLLIST_PATH_NAME, "w")
        file.write(fulllist)
        file.close()
        print("\nThere is nonempty correct fulllist in task\n")
    else:
        print("\ncorrect fulllist is empty\n")
    
    return 0
#----------------------------------------------------------------------

def get_volumes():
    """
    run mountvol to get all volumes and mount points in system.
    for each volume run fsutil to find out file system.
    return ntfs and fat volumes in format 
    result["guid"] - volume guid, result["mount"] - volume mount, result["fs"] - file system
    """
    #call shell command mountvol
    mountvol_dict = auto_log.get_cmd_output2("mountvol")
    if mountvol_dict["err"] != 0:
        return mountvol_dict["out"]
    
    #parse results
    
    #get volumes guid list
    guid_pattern = re.compile(r'\\\\+.+}\\')
    guid_list = guid_pattern.findall(mountvol_dict["out"])
    count = 1
    #mount unmounted volumes (for chkdsk and fsutil)
    for list in guid_list:
        folder_for_mount = SCRIPTS_RUN[0:3] + "volume" + str(count)
        if os.path.exists(folder_for_mount):
            shutil.rmtree(folder_for_mount)
        os.mkdir(folder_for_mount)
        if auto_log.get_cmd_output2('fsutil fsinfo volumeinfo %s' % (list))["err"] != 0:
            auto_log.get_cmd_output2('mountvol "%s" %s' % (folder_for_mount, list))
        count += 1

    result_list = []
    
    for list in guid_list:
        fsutil_dict = auto_log.get_cmd_output2('fsutil fsinfo volumeinfo %s' % (list))
        if fsutil_dict["err"] == 0:
            split_1 = mountvol_dict["out"].split(list + "\n" + "        ")
            split_2 = split_1[1].split("\n")
            mount = split_2[0]
            
            split_1 = fsutil_dict["out"].split("File System Name : ")
            split_2 = split_1[1].split("\n")
            fs = split_2[0]
            
            volume_info = {"guid": list, "mount": mount, "fs": fs}
            if fs.startswith("NTFS") or fs.startswith("FAT"):
                if not mount.startswith("A:"):
                    result_list.append(volume_info)
    
    return result_list
#----------------------------------------------------------------------

def restart_and_check_volumes(path_name):
    """
    function modifies bootexecute value in registry for auto-check all volumes in bluescreen
    create file path_name - use this file as a flag of function run
    restart pc
    """
    
    #if path_name file exists delete it
    if os.path.exists(path_name):
        os.remove(path_name)
        
    volume_list = get_volumes()
    
    #create value for bootexecute
    bootexecute_value = ""
    for list in volume_list:
        line = "autocheck autochk /p \\??\\" + list["guid"][4:-1] + "\\0"
        bootexecute_value += line
    
    #add standard autocheck autochk * to the end of bootexecute_value
    bootexecute_value += "autocheck autochk *"
    
    #delete bootexecute value in registry
    auto_log.get_cmd_output2('reg delete "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager" /v BootExecute /f')
    
    #write new bootexecute value to registry
    auto_log.get_cmd_output2('reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager" /v BootExecute /t REG_MULTI_SZ /d "%s"' % (bootexecute_value))
    
    #create flag
    file = open(path_name, "w")
    file.close()
    
    #restart system
    auto_utility.call_diskpart(["rescan"])
    
    auto_log.get_cmd_output2('shutdown -r -t 0')
#----------------------------------------------------------------------

def parse_stubact_log():
    """
    function for parsing stubact.log. search in stubact string 'Error N (0xN)'
    """
    id = "parse_stubact_log"
    
    print("\nParse_stubact_log")
    if not os.path.exists(STUBACT_PATH_NAME):
        message = "Parse stubact.log = Can not open " + STUBACT_PATH_NAME
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        return("Parse stubact.log = Can not open " + STUBACT_PATH_NAME)
    try:
        file = open(STUBACT_PATH_NAME, "r")
        data = file.read()
        file.close()
    except:
        return("Parse stubact.log = Can't read " + STUBACT_PATH_NAME)
    error_pattern = re.compile(r'Error: +.+\)')
    error_list = error_pattern.findall(data)
    count = 0
    for error in error_list:
        if ((error.split(" ")[1] != "0") and (error.split(" ")[1] != "69643")):
            message = "Parse stubact.log = Error: " + error.split(" ")[1]
            auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
            print("\nParse_stubact_log. Done!")
            return (message)
        else:
            count += 1
    if count == 0:
        message = "Parse stubact.log = No operations found"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("\nParse_stubact_log. Done!")
        return (message)
    
    try:
        file = open(SCRIPT_PATH_NAME, "r")
        script_data = file.read()
        file.close()
    except:
        return ("Parse stubact.log = Can't read " + SCRIPT_PATH_NAME)
    
    if (script_data.count('call check_error') - script_data.count(SPLIT_STRING)) > data.count('Virtual: 0 (0x0)'):
        message = "Parse stubact.log = not all operations have been executed\n"
        message = message + "number of checkings = " + str(script_data.count('call check_error'))
        message = message + "\n" + "number of scripts = " + str(script_data.count(SPLIT_STRING))
        message = message + "\n" + "number of physical operations = " + str(data.count('Virtual: 0 (0x0)'))
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("\nParse_stubact_log. Done!")
        return ("Parse stubact.log = not all operations have been executed")
    auto_log.write_result(RESULTS_PATH_NAME, "Parse stubact.log = OK", auto_log.STATUS_OK, id)
    print("\nParse_stubact_log. Done!")
    return 0
#----------------------------------------------------------------------

def parse_pwlog_txt():
    """
    just save pwlog log to file and parse it
    """
    id = "parse_pwlog_txt"
    print("\nParse pwlog.txt")
    
    if not os.path.exists(PWLOG_PATH_NAME):
        message = "Parse pwlog.txt = Can not open " + PWLOG_PATH_NAME
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        return(message)
    try:
        file = open(PWLOG_PATH_NAME, "r")
        data = file.read()
        file.close()
    except:
        return("Parse pwlog.txt = Can not read " + PWLOG_PATH_NAME)
    
    lines = data.split("\n")
    
    
    error_list = ['rror']
    #error_list.append('fail')
    #error_list.append('warn')
    
    ignore_list = ['Scanning directories and files for errors']
    
    error_count = 0
    error_output = ""
    for line in lines:
        line_error_count = 0
        for error in error_list:
            line_error_count += line.count(error)
        line_ignore_count = 0
        for ignore in ignore_list:
            line_ignore_count += line.count(ignore)
        error_count = error_count + line_error_count - line_ignore_count
        if (line_error_count - line_ignore_count > 0):
            error_output = error_output + line + "\n"
    
    if error_output == "":
        auto_log.write_result(RESULTS_PATH_NAME, "Parse pwlog.txt = OK", auto_log.STATUS_OK, id)
        print("\nParse pwlog.txt. Done!")
        return 0
    else:
        message = "<b>Parse pwlog.txt = Error! Found " + str(error_count) + " errors\n"
        message = message + "Error output:</b>\n" + error_output
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("\nParse pwlog.txt. Done!")
        return (message)
#----------------------------------------------------------------------

def parse_psi_out_log():
    """
    function for parsing psi.out. search in log string 'Returning: N'
    """
    id = "parse_psi_out_log"
    print("\nParse_psi_out_log")
    if not os.path.exists(SCRIPTS_OUTPUT_PATH_NAME):
        message = "Parse psi.out = Can not open " + SCRIPTS_OUTPUT_PATH_NAME
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        return(message)
    try:
        file = open(SCRIPTS_OUTPUT_PATH_NAME, "r")
        data = file.read()
        file.close()
    except:
        return("Parse psi.out = Can not read " + SCRIPTS_OUTPUT_PATH_NAME)
    error_pattern = re.compile(r'Returning:+.+\.')
    error_list = error_pattern.findall(data)
    count = 0
    for error in error_list:
        success_codes = ["Returning: 0.", "Returning: 69643.", "Returning: 0x0 (Successful operation).", "Returning: 0x1100b (Restart is needed for operations completion)."]
        if error not in success_codes:
            message = "Parse psi.out = Error: " + error[1:-1]
            auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
            print("\nParse_psi_out_log. Done!")
            return (message)
        else:
            count += 1
    if count == 0:
        message = "Parse psi.out = No operations found"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("\nParse_psi_out_log. Done!")
        return (message)
    
    try:
        file = open(SCRIPT_PATH_NAME, "r")
        script_data = file.read()
        file.close()
    except:
        return("Parse psi.out = Can not read " + SCRIPT_PATH_NAME)
    
    virtual_number = script_data.count('call check_error') - script_data.count(SPLIT_STRING)
    physical_number = data.count('check_error') / 2
    
    if virtual_number > physical_number:
        message = "Parse psi.out = not all operations have been executed"
        message = message + "\n" + "number of checkings = " + str(script_data.count('call check_error'))
        message = message + "\n" + "number of scripts = " + str(script_data.count(SPLIT_STRING))
        message = message + "\n" + "number of physical operations = " + str(physical_number)
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("\nParse psi.out. Done!")
        return ("Parse psi.out = not all operations have been executed")
    
    auto_log.write_result(RESULTS_PATH_NAME, "Parse psi.out = OK", auto_log.STATUS_OK, id)
    print("\nParse_psi_out_log. Done!")
    
    return 0
#----------------------------------------------------------------------

def parse_chkdsk_log():
    """
    just save chkdsk log to file and parse it
    """
    id = "parse_chkdsk_log"
    time.sleep(60)
    
    print("\nSave_chkdsk_log")
    data = auto_log.get_cmd_output2('c:\\psloglist.exe -i 1001,26214 application')["out"]
    
    file = open(CHKDSK_ALL, "w")
    file.write(data)
    file.close()
    print("\nSave_chkdsk_log. Done!")
    
    error_list = ['epair', 'orrupt', 'orphane', 'lost', 'valid', 'Fixing incorrect information', "Correcting errors in the master file table's (MFT) DATA attribute"]
    #error_list.append('mft')
    #error_list.append('MFT')
    #error_list.append('Mft')
    #error_list.append('correct')
    #error_list.append('error')
    
    count = 0
    for error in error_list:
        count += data.count(error)
    count += data.count('ecover') - data.count('0 unindexed files recovered')#stupid check - need to use this for win7
    if count == 0:
        auto_log.write_result(RESULTS_PATH_NAME, "Parse chkdsk.log = OK", auto_log.STATUS_OK, id)
        return 0
    else:
        message = "<b>Parse chkdsk.log = Error! Found " + str(count) + " errors\n"
        message = message + "Chkdsk log:</b>\n" + data
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        return (message)
#----------------------------------------------------------------------

def parse_bluescreen_log():
    """
    function for parsing bluescreen.log. search in log string 'result Successful operation 0x0'
    """
    id = "parse_bluescreen_log"
    print("\nParse_bluescreen.log")
    if not os.path.exists(BLUESCREEN_PATH_NAME):
        message = "Parse bluescreen.log = Can not open " + BLUESCREEN_PATH_NAME
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        return(message)
    try:
        file = open(BLUESCREEN_PATH_NAME, "r")
        data = file.read()
        file.close()
    except:
        return("Parse bluescreen.log = Can not read " + BLUESCREEN_PATH_NAME)
    error_pattern = re.compile(r'stubAct.+')
    error_list = error_pattern.findall(data)
    count = 0
    
    for error in error_list:
        if not error.endswith("result Successful operation 0x0"):
            print(error)
            message = "Parse bluescreen.log = Error: " + error
            auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
            print("\nParse bluescreen.log. Done!")
            return (message)
        else:
            count += 1
    if count == 0:
        message = "Parse bluescreen.log = No operations found"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        print("ok")
        print("\nParse bluescreen.log. Done!")
        return (message)
    auto_log.write_result(RESULTS_PATH_NAME, "Parse bluescreen.log = OK", auto_log.STATUS_OK, id)
    print("\nParse bluescreen.log. Done!")
    
    return 0
#----------------------------------------------------------------------

def check_diskette_full():
    """
    return 0 if diskette is not full
    """
    test_file_path_name = "a:\\test_full.txt"
    file = open(test_file_path_name, "w")
    data = "just some text"
    file.write(data)
    file.close()
    file = open(test_file_path_name, "r")
    data1 = file.read()
    file.close()
    os.remove(test_file_path_name)
    if data == data1:
        return 0
    else:
        return ("diskette is full")
#----------------------------------------------------------------------

def copy_logs():
    """
    copy logs from floppy to folder FOLDER_FOR_LOGS
    """
    id = "copy_logs"
    if os.path.exists(FOLDER_FOR_LOGS):
        shutil.rmtree(FOLDER_FOR_LOGS)
    shutil.copytree("a:\\", FOLDER_FOR_LOGS)
    
    auto_log.evt_safe_system('c:\\psloglist.exe', FOLDER_FOR_LOGS + "\\system_evt.txt", RESULTS_PATH_NAME)
    auto_log.evt_safe_application('c:\\psloglist.exe', FOLDER_FOR_LOGS + "\\application_evt.txt", RESULTS_PATH_NAME)
    
    if os.path.exists(LAYOUT_INI_PATH_NAME):
        shutil.copy2(LAYOUT_INI_PATH_NAME, FOLDER_FOR_LOGS + "\\layout.ini")
    if os.path.exists(CHKDSK_AFTER_BLUESCREEN):
        shutil.copy2(CHKDSK_AFTER_BLUESCREEN, FOLDER_FOR_LOGS + "\\" + CHKDSK_AFTER_BLUESCREEN)
    if os.path.exists(CHKDSK_ALL):
        shutil.copy2(CHKDSK_ALL, FOLDER_FOR_LOGS + "\\" + CHKDSK_ALL)
    if os.path.exists(CORRECT_FULLLIST_PATH_NAME):
        shutil.copy2(CORRECT_FULLLIST_PATH_NAME, FOLDER_FOR_LOGS + "\\correct_fulllist.txt")
    if check_diskette_full() != 0:
        message = "Diskette is not full = Diskette is full!!!"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
    else:
        auto_log.write_result(RESULTS_PATH_NAME, "Diskette is not full = OK", auto_log.STATUS_OK, id)
#----------------------------------------------------------------------

def copy_logs_and_shutdown():
    """
    copy logs and shutdown
    """
    copy_logs()
    #shutdown
    auto_utility.call_diskpart(["rescan"])
    auto_log.get_cmd_output2('shutdown -s -t 0')
#----------------------------------------------------------------------

def run_next_script():
    id = "run_next_script"
    scripts_list = split_scripts(SCRIPT_PATH_NAME)
    if scripts_list == []:
        message = RESULT_STRING_ERROR + " Can't find script for tests"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        copy_logs_and_shutdown()
        exit(err_no_script)
    
    if not os.path.exists(SCRIPTS_OUTPUT_PATH_NAME):
        file = open(SCRIPTS_OUTPUT_PATH_NAME, "a")
        file.close()
    
    count = 0
    for script in scripts_list:
        count += 1
        file = open(SCRIPTS_OUTPUT_PATH_NAME, "r")
        data = file.read()
        file.close()
        
        if data.count(script) == 0:
            file = open(SCRIPTS_OUTPUT_PATH_NAME, "a")
            data = "\n" + script + "\n"
            #input("write " + script + " to " + SCRIPTS_OUTPUT_PATH_NAME)
            file.write(data)
            file.close()
            
            #run script
            print("\nRun scripts.exe.")
            if not os.path.exists(SCRIPT_PATH_NAME):
                message = RESULT_STRING_ERROR + " Scripts.exe start = Error: Can not open " + SCRIPT_PATH_NAME
                auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
                copy_logs_and_shutdown()
                exit(err_no_scripts)
            auto_log.write_result(RESULTS_PATH_NAME, "Scripts.exe exists = OK", auto_log.STATUS_OK, id)
            
            #run start.py before script
            if os.path.exists(START_PY_PATH_NAME):
                print("run " + START_PY_PATH_NAME + "\n")
                start_command = '"%s" "%s"' % (python_exe, START_PY_PATH_NAME)
                check_result = auto_log.get_cmd_output2(start_command)
                if check_result["err"] == 0:
                    auto_log.write_result(RESULTS_PATH_NAME, "START_PY_SCRIPT = OK\n", auto_log.STATUS_OK, id)
                else:
                    message = "START_PY_SCRIPT = Error " + check_result["out"] + "\n"
                    auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
                print("run " + START_PY_PATH_NAME + "Done!\n")
            else:
                print("There is no " + START_PY_PATH_NAME + "\n")
            #----------------------------------------------------------------------
            
            #command = '""%s" "%s" -oa "%s" --verbose --cutprogress --dontchecklocks"' % (SCRIPTS_RUN, script, SCRIPTS_OUTPUT_PATH_NAME)
            #run_script = os.system(command)
            command = '"%s" "%s" -oa "%s" --verbose --cutprogress --dontchecklocks' % (SCRIPTS_RUN, script, SCRIPTS_OUTPUT_PATH_NAME)
            #-----------------------------------
            t0 = time.time()
            print("scripts.exe " + script + "\nPlease wait...")
            result = auto_log.get_cmd_output2(command)
            #-----------------------------------
            run_script = result["err"]
            #-----------------------------------
            print("\nRun scripts.exe. Done!")
            if run_script == 0:#scripts completed succesfully and without restart
                print("\nMove to the next script")
            elif run_script == 69643:#just wait scripts.exe will restart pc
                print("Scripts.exe request restart to bluescreen")
                exit(err_reboot_request)
            elif run_script == -1073741510:
                exit(err_reboot_request)
            elif run_script == 1073807364:
                exit(err_reboot_request)
            else:
                message = RESULT_STRING_ERROR + " Scripts.exe run = Error: " + str(run_script)
                auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
                copy_logs_and_shutdown()
                exit(err_scripts_failed)
            #----------------------------------------------------------------------
    if count == len(scripts_list):
        return "completed"
    else:
        return "not_completed"
#----------------------------------------------------------------------

def split_scripts(script_path_name):
    if not os.path.exists(script_path_name):
        return []
    file = open(script_path_name, "r")
    data = file.read()
    file.close()

    count = 0
    scripts_list = []
    for script in data.split(SPLIT_STRING):
        if count != 0:
            script_name = script_path_name[0:-4] +"_" + str(count) + ".psl"
            if not os.path.exists(script_name):
                file = open(script_name, "w")
                script = SPLIT_STRING + script
                file.write(script)
                file.close()
            scripts_list.append(script_name)
        count += 1
    return scripts_list
#----------------------------------------------------------------------

def run_fulllist():
    print("\nRunning FULLLIST(-1,-1)")
    script = SCRIPTS_RUN[0:3] + "fulllist.psl"
    file = open(script, "w")
    file.write("FULLLIST(-1,-1)")
    file.close()
    
    command = '"%s" "%s"' % (SCRIPTS_RUN, script)
    data = auto_log.get_cmd_output2(command)["out"]
    file = open(FULLLIST_PATH_NAME, "w")
    file.write(data)
    file.close()
    print("\nRunning FULLLIST(-1,-1). Done!")
    return 0
#----------------------------------------------------------------------

def run_test():
    id = "run_test"
    #input("Start")
    if not os.path.exists(SCRIPTS_OUTPUT_PATH_NAME):
        #if pci.out does not exist, we will run script
        #----------------------------------------------------------------------
        parse_task()
        #----------------------------------------------------------------------
        
        print("\nChange layout.ini.")
        if not os.path.exists(LAYOUT_INI_PATH_NAME):
            message = RESULT_STRING_ERROR + " Cannot open " + LAYOUT_INI_PATH_NAME
            auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
            copy_logs_and_shutdown()
            exit(err_no_layout)
        auto_utility.hdm_change_layout_ini_key(LAYOUT_INI_PATH_NAME, "Write logs into Bluescrn", "on", RESULTS_PATH_NAME)
        auto_utility.hdm_change_layout_ini_key(LAYOUT_INI_PATH_NAME, "Logs directory", '"a:\\"', RESULTS_PATH_NAME)
        auto_utility.hdm_change_layout_ini_key(LAYOUT_INI_PATH_NAME, "Disable FDisk log", "on", RESULTS_PATH_NAME)
        print("\nChange layout.ini. Done!")
        time.sleep(120)
        #----------------------------------------------------------------------
        
        #clear application.evt log
        auto_log.evt_clear_system('c:\\psloglist.exe', RESULTS_PATH_NAME)
        auto_log.evt_clear_application('c:\\psloglist.exe', RESULTS_PATH_NAME)
        #----------------------------------------------------------------------
    
    #input("before running script")
    run_scripts = "not_completed"
    while run_scripts != "completed":
        #input("before running next script")
        run_scripts = run_next_script()
    
    run_fulllist()
    
    if not os.path.exists(CKDSK_FLAG_PATH_NAME):
        restart_and_check_volumes(CKDSK_FLAG_PATH_NAME)
        exit(err_reboot_request)
    
    if os.path.exists(EXCEPT_PATH_NAME):
        message = RESULT_STRING_ERROR + " There is exception in bluescreen!!!"
        auto_log.write_result(RESULTS_PATH_NAME, message, auto_log.STATUS_ERROR, id)
        copy_logs_and_shutdown()
        exit(err_except_in_bluescreen)
    auto_log.write_result(RESULTS_PATH_NAME, "No exception in bluescreen = OK", auto_log.STATUS_OK, id)
    
    error_count = 0
    error = parse_chkdsk_log()
    if error != 0:
        error_count += 1
    
    error = parse_stubact_log()
    if error != 0:
        error_count += 1
        result = RESULT_STRING_ERROR + " " + error
        auto_log.write_result(RESULTS_PATH_NAME, result, auto_log.STATUS_ERROR, id)
    
    error = auto_log.hdm_parse_stubact(STUBACT_PATH_NAME, RESULTS_PATH_NAME)
    if error != 0:
        error_count += 1
    
    error = parse_pwlog_txt()
    if error != 0:
        error_count += 1
    
    error = parse_psi_out_log()
    if error != 0:
        error_count += 1
    
    if os.path.exists(BLUESCREEN_PATH_NAME):
        error = parse_bluescreen_log()
        if error != 0:
            error_count += 1
    
    error = check_diskette_full()
    
    if os.path.exists(END_PY_PATH_NAME):
        print("run " + END_PY_PATH_NAME + "\n")
        end_command = '"%s" "%s"' % (python_exe, END_PY_PATH_NAME)
        check_result = auto_log.get_cmd_output2(end_command)
        if check_result["err"] == 0:
            auto_log.write_result(RESULTS_PATH_NAME, "END_PY_SCRIPT = OK\n", auto_log.STATUS_OK, id)
        else:
            error_count += 1
            auto_log.write_result(RESULTS_PATH_NAME, "END_PY_SCRIPT = Error " + check_result["out"] + "\n", auto_log.STATUS_ERROR, id)
        print("run " + END_PY_PATH_NAME + " Done!\n")
    else:
        print("There is no " + END_PY_PATH_NAME + "\n")
    
    if os.path.exists(CORRECT_FULLLIST_PATH_NAME):
        result = compare_fulllist(CORRECT_FULLLIST_PATH_NAME, FULLLIST_PATH_NAME)
        if result == 0:
            auto_log.write_result(RESULTS_PATH_NAME, "END_PY_SCRIPT = OK\n", auto_log.STATUS_OK, id)
        else:
            error_count += 1
            auto_log.write_result(RESULTS_PATH_NAME, "COMPARE FULLLIST WITH CORRECT = Error " + result + "\n", auto_log.STATUS_ERROR, id)
    else:
        print("There is no " + CORRECT_FULLLIST_PATH_NAME + "\n")
    
    if error_count != 0:
        result = RESULT_STRING_ERROR + " " + str(error_count) + " errors found"
    else:
        auto_log.write_result(RESULTS_PATH_NAME, RESULT_STRING_OK, auto_log.STATUS_OK, id)
    copy_logs_and_shutdown()
    
    return 0
#----------------------------------------------------------------------

auto_utility.call_diskpart(["rescan"])
auto_log.get_cmd_output2("mountvol")

check_result = auto_log.get_cmd_output2("chkdsk a: /f /r")
count = 0
while check_result["err"] != 0:
    time.sleep(15)
    check_result = auto_log.get_cmd_output2("chkdsk a: /f /r /x")
    print(str(check_result["err"]), "\n", check_result["out"])
    if check_result["err"] != 0:
        count += 1
    if count > CHECK_FLOPPY_N:
        exit(err_no_format)

if check_result["err"] == 0:
    result = run_test()

